#include "../logs/qywlog.h"

// 日志器扩展使用样例
enum class TimeGap
{
  GAP_SECOND,
  GAP_MINUTE,
  GAP_HOUR,
  GAP_DAY
};
class RollByTimeSink : public qywlog::LogSink
{
  public:
  RollByTimeSink(const std::string &basename, TimeGap gap_type)
    :_basename(basename)
  {
    switch(gap_type)
    {
      case TimeGap::GAP_SECOND:
        _gap_size = 1; break;
      case TimeGap::GAP_MINUTE:
        _gap_size = 60; break;
      case TimeGap::GAP_HOUR:
        _gap_size = 3600; break;
      case TimeGap::GAP_DAY:
        _gap_size = 3600*24; break;
    }
    _cur_gap = _gap_size==1 
      ? qywlog::util::Date::now() 
      : qywlog::util::Date::now() % _gap_size;//获取当前文件创建时，是第几个时间段
    std::string pathname = createNewFile();
    qywlog::util::File::createDirectory(qywlog::util::File::path(pathname));
    _ofs.open(pathname,std::ios::binary | std::ios::app);
    assert(_ofs.is_open());
  }
  void log(const char *data, size_t len) override
  {
    time_t cur = qywlog::util::Date::now();// 获取当前的时间码
    if((cur % _gap_size) != _cur_gap)
    {
      _ofs.close();
      std::string pathname = createNewFile();
      _ofs.open(pathname,std::ios::binary | std::ios::app);
      assert(_ofs.is_open());
     _cur_gap = _gap_size==1 
      ? qywlog::util::Date::now() 
      : qywlog::util::Date::now() % _gap_size;//获取当前文件创建时，是第几个时间段
    }
    _ofs.write(data, len);
    assert(_ofs.good());
  }
  private:
  std::string createNewFile()
  {
    time_t t = qywlog::util::Date::now();
    struct tm lt;
    localtime_r(&t, &lt);
    std::stringstream pathname;
    pathname << _basename;
    pathname << lt.tm_year + 1900;
    pathname << lt.tm_mon + 1;
    pathname << lt.tm_mday;
    pathname << lt.tm_hour;
    pathname << lt.tm_min;
    pathname << lt.tm_sec;
    pathname << ".log";
   return pathname.str(); 
  }
  private:
  std::string _basename;
  std::ofstream _ofs;
  size_t _gap_size;
  size_t _cur_gap;
};

  void test_log(const std::string &name)
  {  
    // 默认root日志器输出
    FATAL("%s", "开始测试");
    // 自定义日志器输出
    qywlog::Logger::ptr logger = qywlog::LoggerManager::getInstance().getLogger(name);
    logger->debug("%s", "测试日志");
    logger->info("%s", "测试日志");
    logger->warn("%s", "测试日志");
    logger->error("%s", "测试日志");
    logger->fatal("%s", "测试日志");
    // 默认root日志器输出
    FATAL("%s", "测试完毕");   
  }

int main()
{
  // 日志器模块管理器测试 + 全局单例模式下日志器的建造者
  std::unique_ptr<qywlog::LoggerBuilder> builder(new qywlog::GlobalLoggerBuilder());
  builder->buildLoggerName("async_logger");
  builder->buildLoggerLevel(qywlog::LogLevel::value::DEBUG);
  builder->buildFormatter("[%c][%f:%l]%m%n");
  builder->buildLoggerType(qywlog::LoggerType::LOGGER_ASYNC);
  builder->buildSink<RollByTimeSink>("./logfile/roll-async-by-time",TimeGap::GAP_SECOND);
  builder->build();

  size_t cur = qywlog::util::Date::now();
  while(qywlog::util::Date::now() < cur + 5)
  {
    test_log("async_logger");
    usleep(1000);
  }

  return 0;
}

